package com.ruoyi.api.controller;

import com.ruoyi.api.exception.VimBaseException;
import com.ruoyi.api.service.VimUnCountService;
import com.ruoyi.api.service.VimUserApiService;
import com.ruoyi.api.vo.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.vim.service.IImFriendService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 乐天
 */

/**
 * 好友信息处理
 */
@RestController
@RequestMapping("/api/sys/friends")
public class FriendController {

    @Resource
    private VimUserApiService vimUserApiService;

    @Resource
    private VimUnCountService vimUnCountService;

    @GetMapping
    public AjaxResult list(){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<Usertest> list = vimUserApiService.getFriend(user.getUserId());
        return  AjaxResult.success(list);
    }

    /**
     * 添加好友
     * @param user
     * @return
     */
    @PostMapping(value = "add")
    public AjaxResult add(@RequestBody User user){
        try {
            String friendId = user.getId();
            System.out.println(friendId + "====================");
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            if(Long.valueOf(friendId) == sysUser.getUserId()){
                return AjaxResult.error("对象是您自己哟，请换个他人手机号输入");
            }
            return  AjaxResult.success(vimUserApiService.addFriends(friendId,String.valueOf(sysUser.getUserId())));
        } catch (Exception e) {
            return AjaxResult.error("您已添加过该好友");
        }
    }

    /**
     * 删除好友
     * @param friendIds
     * @return
     */
    @PostMapping(value = "delete")
    public AjaxResult delete(@RequestBody FriendId friendIds){
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        return  AjaxResult.success(vimUserApiService.delFriends(friendIds.getFriendId(),String.valueOf(sysUser.getUserId())));
    }

    /**
     * 判断发送者和用户是否是好友关系
     * @param charId
     * @param userId
     * @return
     */
    @GetMapping(value = "bofriend")
    public AjaxResult bofriend(@RequestParam String charId,
                               @RequestParam String userId){
        vimUserApiService.selectfriends(charId,userId);
        return AjaxResult.success();
    }

    /**
     * 查询未读消息条数和最后一条消息
     * @param userId
     * @return
     */
    @PostMapping(value = "unread")
    public AjaxResult unread(@RequestBody String userId){
        List<UnMessage> messages = new ArrayList<>();
        List<String> list = vimUserApiService.selectfriend(userId);
        for (String aLong : list) {
            UnMessage unMessage = vimUnCountService.selects(userId,aLong);
            messages.add(unMessage);
        }
        return AjaxResult.success(messages);
    }

}
